<template>
	<view>
		<!-- 导航栏区域 -->
		<view class="navBar-class">
			<!-- 返回按钮 -->
			<tn-button style="color: black;width: 35px; height: 35px; font-size: 15px;" :border="false"
				@click="handleReturn">
				<text class="tn-icon-left" />
			</tn-button>
			<!-- 商品名称 -->
			<view style="font-size: 15px;margin-right: auto;">{{ product.name }}</view>
		</view>
		<!-- 卖家信息区域 -->
		<view style="border-radius:25px;height: 45px;width: 84%;display: flex;align-items:center; margin-left: 8%;"
			@click="dian(seller.userId)">
			<!-- 卖家头像 -->
			<tn-avatar :src="seller.avatarUrl" size="lg" style="margin-left: 3%;" />
			<!-- 卖家昵称或默认称呼 -->
			<text style="margin-left: 3%;">{{ seller.nickname != "" ? seller.nickname : "神秘用户" }}</text>
		</view>
		<!-- 商品详情区域 -->
		<view style="width: 90%; margin-left: 5%;height: 1000px;">
			<view style="width: 90%;margin-left: 5%;">
				<!-- 商品价格和邮费信息 -->
				<view>
					<text style="color: #FF4400; font-size:25px;">￥{{ product.price }}</text>
					<text
						style="margin-left: 15px;color: #343434;">{{ product.delivery === "1" ? "包邮" : "买家自费" }}</text>
					<text style="margin-left: 15px;color: #676767;font-size: 18px;">库存剩余:</text>
					<text style="margin-left: 8px;">{{ product.number }}</text>
				</view>
				<!-- 商品简述 -->
				<view>
					<text style="font-size: 15px;">
						{{ product.brief }}
					</text>
				</view>
			</view>
			<!-- 商品图片 -->
			<view style="width: 90%;margin-left: 5%;border-radius: 20px;margin-top: 10px;">
				<image :src='product.img || "/static/5c750d6f977fe.png"' style="width: 100%;border-radius: 20px;"
					mode="aspectFit" />
			</view>
			<!-- 发布者信息 -->
			<view class="publisher-info" v-if="product.publisher">
				<image :src="product.publisher.avatar" class="publisher-avatar"></image>
				<text class="publisher-name">{{ product.publisher.nickname }}</text>
			</view>
		</view>
		<!-- 底部按钮区域 -->
		<view class="bottom">
			<!-- 收藏按钮 -->
			<view class="collect-btn" @tap="handleCollect">
				<text class="tn-icon-star"
					:class="{'icon-uncollected': !isCollected, 'icon-collected': isCollected}"></text>
			</view>
			<!-- 我想要按钮 -->
			<tn-button backgroundColor="#FFE60F" class="want-btn" @click="sendMessage">我想要</tn-button>
		</view>
	</view>
</template>

<script>
	import messageApi from '@/utils/api';

	export default {
		data() {
			return {
				productId: '',
				product: {
					id: 0,
					name: "",
					img: null,
					brief: "",
					price: 0,
					delivery: 1,
					userId: 0,
					number: 0
				},
				seller: {
					userId: 0,
					nickname: "",
					avatarUrl: ""
				},
				loading: false,
				errorMessage: '',
				isCollected: false,
			};
		},
		onLoad(option) {
			// 页面加载时获取商品信息
			this.show(option);
			// 检查收藏状态
			this.checkCollectStatus();
		},
		methods: {
			dian(userid) {
				if (userid===0) {
					uni.showToast({
						title: '无法获取卖家信息',
						icon: 'none'
					});
					return;
				}else{
				uni.navigateTo({
					url: "/pages/Information/homePage/homePage?userId=" + userid
				})
				}
			},
			/**
			 * 返回上一页
			 */
			handleReturn() {
				uni.navigateBack({
					delta: 1
				});
			},
			/**
			 * 获取商品详细信息
			 * @param {Object} content - 页面加载参数，包含商品ID
			 */
			show(content) {
				let that = this;
				this.loading = true;
				this.errorMessage = '';
				this.productId = content.id;
				// 请求商品信息
				uni.request({
					url: this.baseUrl + "/admin/goods/detail?id=" + content.id,
					success: function(res) {
						if (res.data.data) {
							// 更新商品信息
							that.product.id = res.data.data.goods.id
							that.product.name = res.data.data.goods.name;
							that.product.img = res.data.data.goods.picUrl;
							that.product.price = res.data.data.goods.counterPrice;
							that.product.brief = res.data.data.goods.brief;
							that.product.delivery = res.data.data.attributes.filter(item => {
								return item.attribute === "delivery"
							})[0]?.value || "0"
							that.product.userId = res.data.data.attributes.filter(item => {
								return item.attribute === "userId"
							})[0]?.value || "0"
							if (res.data.data.products[0] != undefined)
								that.product.number = res.data.data.products[0].number
							// 获取卖家信息
							if (that.product.userId) {
								that.getSeller(that.product.userId)
							}
							// 添加浏览记录
							that.addHistoryRecord(that.product)
						}
					},
					fail(e) {
						console.error(e);
						that.errorMessage = '获取商品信息失败';
					},
					complete() {
						that.loading = false;
					}
				});
			},
			/**
			 * 获取卖家信息
			 * @param {String} userId - 卖家用户ID
			 */
			getSeller(userId) {
				let that = this
				// 请求卖家信息
				uni.request({
					url: this.baseUrl + "/wx/user/getUser?userId=" + userId,
					success(res) {
						if (Object.keys(res.data.data).length != 0) {
							// 更新卖家信息
							that.seller.userId = res.data.data.user.id
							that.seller.nickname = res.data.data.user.nickname
							that.seller.avatarUrl = res.data.data.user.avatar
						}
					}
				})
			},
			/**
			 * 发送消息给卖家
			 */
			sendMessage() {
				if (!this.seller.userId) {
					uni.showToast({
						title: '无法获取卖家信息',
						icon: 'none'
					});
					return;
				}
				// 构建聊天初始消息
				const chatInfo = {
					sellerId: this.seller.userId,
					sellerName: this.seller.nickname || "神秘用户",
					sellerAvatar: this.seller.avatarUrl,
					lastMessage: `我对商品"${this.product.name}"感兴趣`,
					productInfo: {
						id: this.product.id,
						name: this.product.name,
						img: this.product.img,
						price: this.product.price,
						brief: this.product.brief,
						delivery: this.product.delivery === "1" ? "包邮" : "买家自费"
					}
				};

				// 跳转到聊天详情页
				uni.navigateTo({
					url: `/pages/message/ChatDetail`,
					success: function(res) {
						res.eventChannel.emit('chatInfo', {
							...chatInfo,
							partnerId: chatInfo.sellerId,
							partnerName: chatInfo.sellerName,
							partnerAvatar: chatInfo.sellerAvatar,
							productId: chatInfo.productInfo.id
						});
						// 同时更新消息列表
						const pages = getCurrentPages();
						const messageListPage = pages.find(page => page.route === 'pages/message/messageList');
						if (messageListPage) {
							messageListPage.$vm.addNewChat({
								partnerId: chatInfo.sellerId,
								partnerName: chatInfo.sellerName,
								partnerAvatar: chatInfo.sellerAvatar,
								lastMessage: chatInfo.lastMessage,
								productId: chatInfo.productInfo.id
							});
						}
					}
				});
			},
			/**
			 * 添加商品浏览记录
			 * @param {Object} product - 商品信息
			 */
			addHistoryRecord(product) {
				let user = uni.getStorageSync("userInfo")
				// 请求添加浏览记录
				uni.request({
					url: this.baseUrl + "/wx/histories/addHistoryRecord",
					method: 'POST',
					data: {
						userId: user.id,
						goodId: product.id,
						picUrl: product.img
					},
					success(res) {

					}
				})
			},
			// 检查收藏状态
			async checkCollectStatus() {
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo) return;

				try {
					const res = await uni.request({
						url: this.baseUrl + `/wx/collect/list/${userInfo.id}`,
						method: 'GET',
						data: {
							type: 0,
							valueId: this.product.id
						}
					});

					if (res.data.errno === 0) {
						// 检查商品是否在收藏列表中
						const collectList = res.data.data.list;
						this.isCollected = collectList.some(item => item.valueId === this.product.id);
					}
				} catch (error) {
					console.error('获取收藏状态失败:', error);
				}
			},
			// 处理收藏/取消收藏
			async handleCollect() {
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				try {
					const url = `/wx/collect/addordelete/${userInfo.id}`; // 修改为正确的接口
					const res = await uni.request({
						url: this.baseUrl + url,
						method: 'POST',
						data: {
							type: 0,
							valueId: this.product.id
						}
					});

					if (res.data.errno === 0) {
						this.isCollected = !this.isCollected;
						uni.showToast({
							title: this.isCollected ? '收藏成功' : '取消收藏',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: res.data.errmsg,
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('收藏操作失败:', error);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style>
	/* 导航栏样式 */
	.navBar-class {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 15%;
		height: auto;
	}

	/* 底部按钮样式 */
	.bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		background-color: white;
		height: 50px;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 0 20rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	/* 收藏按钮样式 */
	.collect-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 80rpx;
		height: 80rpx;
		margin-right: 20rpx;
		border-radius: 50%;
		background-color: #ffffff;
	}

	.icon-uncollected {
		font-size: 50rpx;
		color: #ffffff;
		-webkit-text-stroke: 2px #000;
	}

	.icon-collected {
		font-size: 50rpx;
		color: #ff4400;
		-webkit-text-stroke: 1px #ff4400;
	}

	/* 我想要按钮样式 */
	.want-btn {
		height: 30px;
		margin-top: 0;
		border-radius: 20px;
	}

	/* 发布者信息样式 */
	.publisher-info {
		display: flex;
		align-items: center;
		margin-top: 10px;
	}

	.publisher-avatar {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.publisher-name {
		font-size: 15px;
	}
</style>